/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.ext.zul;

import cn.easyplatform.web.ext.*;
import org.zkoss.lang.Strings;
import org.zkoss.zk.ui.ext.Disable;
import org.zkoss.zkmax.zul.Chosenbox;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class ChosenboxExt extends Chosenbox implements ZkExt, Cacheable,
        Reloadable, Assignable, Disable, Queryable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    /**
     * 查询语句,结果column个数可以有1-3个,当1个的时候value和label共用，2个时分别表示value和labe
     */
    private Object _query;

    /**
     * 数据连接的资源id
     */
    private String _dbId;

    /**
     * 在列表中是否要缓存本组件
     */
    private boolean _cache;

    /**
     * 在显示时是否要马上执行查询
     */
    private boolean _immediate = true;

    /**
     * 初始值
     */
    private transient String _value;

    /**
     * 过滤表达式
     */
    private String _filter;
    /**
     * 是否必需重新加载
     */
    private boolean _force;

    @Override
    public boolean isForce() {
        return _force;
    }

    public void setForce(boolean force) {
        this._force = force;
    }

    public String getFilter() {
        return _filter;
    }

    public void setFilter(String filter) {
        this._filter = filter;
    }

    /**
     * @return
     */
    public boolean isImmediate() {
        return _immediate;
    }

    /**
     * @param immediate
     */
    public void setImmediate(boolean immediate) {
        this._immediate = immediate;
    }

    public Object getQuery() {
        return _query;
    }

    public void setQuery(Object query) {
        this._query = query;
    }

    public String getDbId() {
        return _dbId;
    }

    public void setDbId(String dbId) {
        this._dbId = dbId;
    }

    public void setCache(boolean cache) {
        this._cache = cache;
    }

    @Override
    public void setValue(Object value) {
        if (getModel() == null)
            this._value = (String) value;
        else if (Strings.isBlank((String) value)) {
            setSelectedIndex(-1);
        } else if (getModel() != null) {
            String sep = getSeparator();
            if (sep == null)
                sep = ",";
            String[] values = value.toString().split("\\" + sep);
            List<PairItem> sels = new ArrayList<PairItem>();
            for (String val : values)
                sels.add(new PairItem(val));
            try {//web bug
                setSelectedObjects(sels);
            } catch (Exception ex) {
            }
        }
    }

    @Override
    public Object getValue() {
        if (getModel() == null)
            return this._value;
        Set<PairItem> sels = getSelectedObjects();
        if (sels != null) {
            String sep = getSeparator();
            if (sep == null)
                sep = ",";
            StringBuilder sb = new StringBuilder();
            Iterator<PairItem> itr = sels.iterator();
            while (itr.hasNext()) {
                PairItem item = itr.next();
                sb.append(item.getValue());
                if (itr.hasNext())
                    sb.append(sep);
            }
            return sb.toString();
        } else
            return null;
    }

    public String getLabel() {
        if (getModel() == null)
            return null;
        Set<PairItem> sels = getSelectedObjects();
        if (sels != null) {
            String sep = getSeparator();
            if (sep == null)
                sep = ",";
            StringBuilder sb = new StringBuilder();
            Iterator<PairItem> itr = sels.iterator();
            while (itr.hasNext()) {
                PairItem item = itr.next();
                sb.append(item.getLabel());
                if (itr.hasNext())
                    sb.append(sep);
            }
            return sb.toString();
        } else
            return null;
    }

    public Object getSelectedValue() {
        return getValue();
    }

    @Override
    public void reload() {
        Widget ext = (Widget) getAttribute("$proxy");
        ext.reload(this);
    }

    public void selectAll() {
        ListModel<PairItem> model = this.getModel();
        setSelectedObjects(((ListModelList<PairItem>) model).getInnerList());
    }

    @Override
    public boolean isCache() {
        return _cache;
    }

    public void setFormat(String format) {
        this.setSeparator(format);
    }

    public String getFormat() {
        return this.getSeparator();
    }
}
